import React, { useState } from "react";
import styles from "../css/add.module.css";
/**
 * 双向绑定的写法
 * @returns
 */
const add: React.FC<{
  onSumCalculated: (data: {
    id: number;
    title: string;
    count: string;
    time: string;
  }) => void;
}> = (props) => {
  const [date, setDate] = useState("");
  const [content, setContent] = useState("");
  const [time, setTime] = useState("");

  const jsonData = {
    id: new Date().getTime(),
    title: content,
    count: time,
    time: time,
  };

  const getDate = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
    setDate(e.target.value);
  };

  const getContent = (e: React.ChangeEvent<HTMLInputElement>) => {
    setContent(e.target.value);
  };

  const getTime = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTime(e.target.value);
  };

  /**
   * 表单的submit事件代替onclick事件
   * @param e
   */
  const formSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    // 阻止默认的form提交事件，会有跳转行为
    e.preventDefault();
    console.log("提交数据为：", jsonData);
    // 通过事件将jsonData传递给父组件
    props.onSumCalculated(jsonData);
    //点击提交按钮后，表单内容清空
    setContent("");
    setTime("");
    setDate("");
  };

  return (
    <div className={styles.add}>
      <form action="/login" method="post" onSubmit={formSubmit}>
        <label htmlFor="date">日期：</label>
        <input
          type="date"
          onChange={getDate}
          id="date"
          name="date"
          value={date}
        />
        <br />
        <label htmlFor="message">内容：</label>
        <input
          type="text"
          onChange={getContent}
          id="message"
          name="message"
          placeholder="内容："
          value={content}
        />
        <br />
        <label htmlFor="pwd">时长：</label>
        <input
          type="text"
          onChange={getTime}
          id="pwd"
          name="password"
          value={time}
        />
        <button type="submit">提交</button>
      </form>
    </div>
  );
};

export default add;
